<script setup>
import commonTable from '@/components/commonTable.vue';
import xmlDialog from '@/components/xml/index.vue';
import showFlowInfo from '@/components/showFlowInfo.vue'
import {
  getDataManagementDataListAsync,
  getFlowXmlAsync,
  deletedFlowInstanceAysnc
} from '@/api/dataManagement.js'
import useStore from '@/stores';
const { useAPIStore } = useStore()
//关键词搜索
const formData = ref({
  key: ''
})


const tableData = ref([])
const tableHeader = ref([

  {
    data: {
      prop: 'proInstId',
      label: '流程实例id',
    },
  },
  {
    data: {
      prop: 'name',
      label: '流程名称',
    },
  },
  {
    data: {
      prop: 'startUserName',
      label: '发起流程的用户昵称',
    },
  },
  {
    data: {
      prop: 'startDate',
      label: '发起流程时间',
    },
  },
  {
    slot: 'isEnd',
    data: {
      label: '完成时间'
    }
  },
  {
    slot: 'operate',
    data: {
      label: '操作'
    }
  }
])
const pagination = ref({
  size: 10,
  total: 10,
  curPage: 1,
  pageSizes: [3, 5, 10, 20]

})
// 表格加载动画
const isLoading = ref(false)

//获取表格数据
const getTabelData = async () => {
  try {
    isLoading.value = true
    const params = {
      key: formData.value.key,
      currPage: pagination.value.curPage,
      pageSize: pagination.value.size
    }
    // 调接口
    const { data: res } = await getDataManagementDataListAsync(params)

    console.log('%c [  ]-85', 'font-size:13px; background:pink; color:#bf2c9f;', res)

    if (res.rows && Array.isArray(res.rows) && res.rows.length) {
      tableData.value = res.rows
    } else {
      tableData.value = []
    }

    pagination.value.total = +res.total
    isLoading.value = false

  } catch (error) {
    isLoading.value = false
    ElMessage.error(error)
    console.log('%c [ error ]-109', 'font-size:13px; background:pink; color:#bf2c9f;', error)
  }
}

//关键字查询| 刷新数据
const searchHandle = () => {
  pagination.value.curPage = 1
  getTabelData()
}


//页大小改变
const handleSizeChange = (val) => {
  pagination.value.size = val
  getTabelData()
}
//切换页
const handleCurrentChange = (val) => {
  pagination.value.curPage = val
  getTabelData()
}

//查看流程图
const getFlowChart = async (info) => {

  console.log('%c [  ]-120', 'font-size:13px; background:pink; color:#bf2c9f;', useAPIStore)
  try {
    const params = {
      ...info
    }
    const xmlRes = await getFlowXmlAsync(params)
    if (xmlRes) {
      const src = `${useAPIStore.img_base_url}lanlu/task/flowImg?processId=${info.proInstId}`
      xml.value = {
        src: src,
        str: xmlRes
      }
      flowChartDialogVisible.value = true
    }
  } catch (error) {
    console.log('%c [ error ]-134', 'font-size:13px; background:pink; color:#bf2c9f;', error)

  }
}


//流程图文件
const xml = ref('')

//用户弹窗标识
const flowChartDialogVisible = ref(false)

const closeDialog = () => {
  flowChartDialogVisible.value = false
}

//预览表单弹窗的数据
const previewData = ref({})
const previewVisible = ref(false)
//预览表单
const previewFormHandle = async (info) => {
  if (!info.json || !JSON.parse(info.json).length) return ElMessage.error(`流程【${info.name}】没有绑定对应的表单，请先进行绑定！`)
  previewData.value = {
    optionList: JSON.parse(info.json)?.map(item => {
      item.data = {
        label: item.label,
        prop: item.fieldName
      }
      return {
        data: {
          label: item.label,
          prop: item.fieldName
        },
        $attrs: item.$attrs,
        component: item.componentName,
        required: item.required
      }
    }),
    title: info.name,
    optionData: info.jsonValue
  }

  previewVisible.value = true
}



//查看流转信息
const descriptionData = ref([])
const descriptionHeader = ref({
  // title: '流程信息',
  column: 1,
  border: true
})
const getFlowInfoList = (info) => {

  if (!info.transferRecords.length) return ElMessage.error(`流程【${info.name}】暂无流转信息！`)
  descriptionData.value = info.transferRecords
  flowInfoListVisible.value = true
}

//流程抽屉
const flowInfoListVisible = ref(false)


//删除
const deletedFlow = async (info) => {
  try {
    const params = {
      ...info
    }
    const res = await deletedFlowInstanceAysnc(params)
    if (res && res.code + '' === '200') {
      ElMessage.success(`成功删除流程【${info.name}】`)
      getTabelData()
    }
  } catch (error) {
    console.log('%c [ error ]-182', 'font-size:13px; background:pink; color:#bf2c9f;', error)

  }
}


onMounted(() => {
  getTabelData()
})

</script>


<template>
  <div class="user-container">
    <el-card>
      <template #header>
        <div class='card-header'>
          <el-form>
            <el-form-item label="流程名称关键词" prop="key">
              <el-input class="search-inp" v-model="formData.key" placeholder="请输入关键字" clearable></el-input>
            </el-form-item>
          </el-form>

          <el-button class="btn-blue" type="primary" plain :icon="Search" @click="searchHandle">
            <el-icon>
              <Search />
            </el-icon>
            <span>查询</span>
          </el-button>
        </div>
      </template>

      <commonTable :tableData="tableData" :tableHeader="tableHeader" :isLoading="isLoading">
        <template #isEnd='{ scope }'>
          <el-tag v-if="scope.endDate" type="success">{{ scope.endDate }}</el-tag>
          <el-tag v-else type="danger">{{ scope.isEnd }}</el-tag>
        </template>

        <template #operate="{ scope }">

          <el-tooltip content="预览表单" placement="bottom">
            <el-button type="success" plain circle @click="previewFormHandle(scope)">
              <el-icon>
                <Edit />
              </el-icon>
            </el-button>
          </el-tooltip>

          <el-tooltip content="查看流程图" placement="bottom">
            <el-button type="warning" plain circle @click="getFlowChart(scope)">
              <el-icon>
                <DataBoard />
              </el-icon>

            </el-button>
          </el-tooltip>

          <el-tooltip content="查看流转信息" placement="bottom">
            <el-button type="primary" plain circle @click="getFlowInfoList(scope)">
              <el-icon>
                <ChatLineSquare />
              </el-icon>
            </el-button>
          </el-tooltip>


          <el-popconfirm title="确定要删除此流程实例吗，删除后相关任务也将被删除，请谨慎操作?" @confirm="deletedFlow(scope)">
            <template #reference>
              <el-button type="danger" plain circle>
                <el-icon>
                  <Delete />
                </el-icon>
              </el-button>
            </template>
          </el-popconfirm>

        </template>
      </commonTable>

      <template #footer>
        <div class="card-footer">
          <el-pagination background layout="total,prev, pager, next, sizes" :total="pagination.total"
            :page-sizes="pagination.pageSizes" :current-page="pagination.curPage" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </div>
      </template>
    </el-card>
  </div>

  <!-- 查看流程图 -->
  <xmlDialog :visible="flowChartDialogVisible" :xml="xml" @closeDialog="closeDialog">
  </xmlDialog>

  <!-- 阅览表单 -->
  <previewForm :visible="previewVisible" :optionList="previewData.optionList" :title="previewData.title"
    @closeDialog="previewVisible = false">
  </previewForm>

  <!-- 流转信息 -->
  <showFlowInfo :visible="flowInfoListVisible" :descriptionData="descriptionData" :descriptionHeader="descriptionHeader"
    @close-drawer="flowInfoListVisible = false"></showFlowInfo>

</template>

<style lang="scss" scoped>
.user-container {

  .card-header {
    display: flex;

    .search-inp {
      width: 200px;
      margin-right: 10px;
    }

    :deep(.el-button) {
      color: #fff;
      width: 100px;
      height: 35px;
      font-size: 16px;
      border-color: #c6c6c6;
    }
  }

  .card-footer {
    display: flex;
    justify-content: flex-end;

  }

  .preview-btn {
    cursor: pointer;
  }


}


:deep(.el-form-item__label) {
  font-weight: 700;
}
</style>